const express = require('express');
var router = express.Router();
const ExcelJS = require('exceljs');
const fs = require('fs');

// 保存本地JSON数据的接口
router.post('/save-json', (req, res) => {
    const { filename, data } = req.body;
    if (!filename || !data) {
        return res.status(400).send('Bad Request: Missing filename or data');
    }

    try {
        fs.writeFileSync(__dirname +`/json/${filename}.json`, JSON.stringify(data));
        res.status(200).send('保存成功');
    } catch (error) {
        console.error('Error saving file:', error);
        res.status(500).send('Internal Server Error');
    }
});

// 读取指定JSON文件的接口
router.get('/read-json/:filename', (req, res) => {
    const { filename } = req.params;
    try {
        const data = fs.readFileSync(__dirname + `/json/${filename}.json`, 'utf8');
        res.send(JSON.parse(data));
    } catch (error) {
        console.error('Error reading file:', error);
        res.status(404).send('File not found');
    }
});

// 返回菜单表的接口
router.get('/file-menu', (req, res) => {
    try {
        const files = fs.readdirSync(__dirname + '/json', { withFileTypes: true })
            .filter(dirent => dirent.isFile() && dirent.name.endsWith('.json'))
            .map(dirent => dirent.name.replace('.json', ''));
        res.send(files);
    } catch (error) {
        console.error('Error reading directory:', error);
        res.status(500).send('Internal Server Error');
    }
});



module.exports = router;